package com.allwees.core.dao.configuration.datapermission;

import com.allwees.core.dao.annotation.NoDataPermission;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class DataPermissionUtil {

    private static Map<String, Boolean> caches = new ConcurrentHashMap<>();

    /**
     *
     * @param id
     * @return
     */
    public static boolean canProcessSql(String id) {
        Boolean required = caches.get(id);
        if (required != null) {
            return required;
        }
        boolean isRequired = true;
        try {
            isRequired = _canProcessSql(id);
        } catch (Exception e) {
            log.error(">>>>>> analysis error", e);
        }
        caches.put(id, isRequired);
        return isRequired;
    }

    /**
     *
     * @param id
     * @return
     * @throws ClassNotFoundException
     */
    private static boolean _canProcessSql(String id) throws ClassNotFoundException {
        int index = id.lastIndexOf(".");
        String className = id.substring(0, index), methodName = id.substring(index + 1);
        Class<?> clz = Class.forName(className);
        Method[] methods = clz.getMethods();
        if (ArrayUtils.isEmpty(methods)) {
            return true;
        }
        Method method = Arrays.stream(methods).filter(m -> m.getName().equals(methodName)).findFirst().get();

        NoDataPermission noRequiredDataPermission = method.getAnnotation(NoDataPermission.class);
        if (noRequiredDataPermission != null) {
            return noRequiredDataPermission.required();
        }
        return true;
    }
}
